<template>
  <div class="roles-page">
    <div class="page-header">
      <h1>Role Management</h1>
      <el-button type="primary" @click="showCreateDialog = true">
        <el-icon><Plus /></el-icon>
        Add Role
      </el-button>
    </div>
    
    <el-card>
      <el-table v-loading="loading" :data="roles" style="width: 100%">
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="name" label="Name" />
        <el-table-column prop="description" label="Description" />
        <el-table-column label="Permissions">
          <template #default="{ row }">
            <el-tag
              v-for="permission in row.permissions.slice(0, 3)"
              :key="permission.id"
              size="small"
              style="margin-right: 5px"
            >
              {{ permission.name }}
            </el-tag>
            <span v-if="row.permissions.length > 3">
              +{{ row.permissions.length - 3 }} more
            </span>
          </template>
        </el-table-column>
        <el-table-column label="Status" width="100">
          <template #default="{ row }">
            <el-tag :type="row.isActive ? 'success' : 'danger'">
              {{ row.isActive ? 'Active' : 'Inactive' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="Actions" width="150">
          <template #default="{ row }">
            <el-button size="small" @click="editRole(row)">
              <el-icon><Edit /></el-icon>
            </el-button>
            <el-button size="small" type="danger" @click="deleteRole(row)">
              <el-icon><Delete /></el-icon>
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    
    <!-- Create/Edit Role Dialog -->
    <el-dialog
      v-model="showCreateDialog"
      :title="editingRole ? 'Edit Role' : 'Create Role'"
      width="700px"
    >
      <el-form
        ref="roleFormRef"
        :model="roleForm"
        :rules="roleRules"
        label-width="120px"
      >
        <el-form-item label="Name" prop="name">
          <el-input v-model="roleForm.name" />
        </el-form-item>
        
        <el-form-item label="Description">
          <el-input v-model="roleForm.description" type="textarea" />
        </el-form-item>
        
        <el-form-item label="Permissions" prop="permissionIds">
          <el-checkbox-group v-model="roleForm.permissionIds">
            <div v-for="group in groupedPermissions" :key="group.resource" class="permission-group">
              <h4>{{ group.resource }}</h4>
              <el-checkbox
                v-for="permission in group.permissions"
                :key="permission.id"
                :label="permission.id"
              >
                {{ permission.name }}
              </el-checkbox>
            </div>
          </el-checkbox-group>
        </el-form-item>
        
        <el-form-item v-if="editingRole" label="Status">
          <el-switch
            v-model="roleForm.isActive"
            active-text="Active"
            inactive-text="Inactive"
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="cancelEdit">Cancel</el-button>
        <el-button type="primary" :loading="saving" @click="saveRole">
          {{ editingRole ? 'Update' : 'Create' }}
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus'
import { Plus, Edit, Delete } from '@element-plus/icons-vue'
import api from '@/api'

interface Permission {
  id: number
  name: string
  description?: string
  resource: string
  action: string
  isActive: boolean
}

interface Role {
  id: number
  name: string
  description?: string
  isActive: boolean
  createdAt: string
  permissions: Permission[]
}

const roles = ref<Role[]>([])
const permissions = ref<Permission[]>([])
const loading = ref(false)
const saving = ref(false)
const showCreateDialog = ref(false)
const editingRole = ref<Role | null>(null)
const roleFormRef = ref<FormInstance>()

const roleForm = reactive({
  name: '',
  description: '',
  permissionIds: [] as number[],
  isActive: true
})

const roleRules: FormRules = {
  name: [
    { required: true, message: 'Please input role name', trigger: 'blur' }
  ]
}

const groupedPermissions = computed(() => {
  const groups: { [key: string]: Permission[] } = {}
  permissions.value.forEach(permission => {
    if (!groups[permission.resource]) {
      groups[permission.resource] = []
    }
    groups[permission.resource].push(permission)
  })
  
  return Object.keys(groups).map(resource => ({
    resource,
    permissions: groups[resource]
  }))
})

const loadRoles = async () => {
  loading.value = true
  try {
    const response = await api.get('/roles')
    roles.value = response.data
  } catch (error) {
    ElMessage.error('Failed to load roles')
  } finally {
    loading.value = false
  }
}

const loadPermissions = async () => {
  try {
    const response = await api.get('/permissions')
    permissions.value = response.data
  } catch (error) {
    ElMessage.error('Failed to load permissions')
  }
}

const editRole = (role: Role) => {
  editingRole.value = role
  roleForm.name = role.name
  roleForm.description = role.description || ''
  roleForm.permissionIds = role.permissions.map(p => p.id)
  roleForm.isActive = role.isActive
  showCreateDialog.value = true
}

const deleteRole = async (role: Role) => {
  try {
    await ElMessageBox.confirm(
      `Are you sure you want to delete role "${role.name}"?`,
      'Confirm Delete',
      {
        confirmButtonText: 'Delete',
        cancelButtonText: 'Cancel',
        type: 'warning'
      }
    )
    
    await api.delete(`/roles/${role.id}`)
    ElMessage.success('Role deleted successfully')
    loadRoles()
  } catch (error: any) {
    if (error !== 'cancel') {
      ElMessage.error('Failed to delete role')
    }
  }
}

const saveRole = async () => {
  if (!roleFormRef.value) return
  
  await roleFormRef.value.validate(async (valid) => {
    if (valid) {
      saving.value = true
      try {
        if (editingRole.value) {
          await api.put(`/roles/${editingRole.value.id}`, roleForm)
          ElMessage.success('Role updated successfully')
        } else {
          await api.post('/roles', roleForm)
          ElMessage.success('Role created successfully')
        }
        
        showCreateDialog.value = false
        loadRoles()
        resetForm()
      } catch (error) {
        ElMessage.error(editingRole.value ? 'Failed to update role' : 'Failed to create role')
      } finally {
        saving.value = false
      }
    }
  })
}

const cancelEdit = () => {
  showCreateDialog.value = false
  resetForm()
}

const resetForm = () => {
  editingRole.value = null
  Object.assign(roleForm, {
    name: '',
    description: '',
    permissionIds: [],
    isActive: true
  })
  roleFormRef.value?.resetFields()
}

onMounted(() => {
  loadRoles()
  loadPermissions()
})
</script>

<style scoped>
.roles-page {
  padding: 0;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h1 {
  margin: 0;
  color: #333;
  font-size: 24px;
  font-weight: 600;
}

.permission-group {
  margin-bottom: 20px;
  padding: 15px;
  border: 1px solid #e6e6e6;
  border-radius: 4px;
}

.permission-group h4 {
  margin: 0 0 10px 0;
  color: #333;
  font-size: 16px;
}

.permission-group .el-checkbox {
  display: block;
  margin: 8px 0;
}
</style>
